(function(window,$,undefined){
	var selector = 'ctpl';
	var element = $('.'+selector);
	var menu_sel = 'ctpl-menu';
	var menu_inner_sel = 'ctpl-menu-inner';
	if(element.length!=1)
		return;
	var ctpl = {
		version:'0.1.0',
		author:'bluishoul',
		target:null,
		icon_width:20,
		cname:function(module){
			var cname = '.'+selector;
			return module?cname+'-'+module:cname;
		},
		sel:function(module){
			return module?selector+'-'+module:selector;
		},
		sel_all:function(module){
			return ['[class^="',this.sel(module),'"]'].join('');
		},
		on:function(events,sel,callback){
			return element.on(events,sel,callback);
		},
		insert: function(myValue) {
			var isElm = myValue.nodeType;
			var selection = window.getSelection();
			var range = selection.getRangeAt();
			range.insertNode(myValue)
		},
		width:function(){
			return $(this.cname()).width()
		},
		onEdit:function(menu_width){
			var target = this.target;
			var self = this;
			self.showMenu(target);
			target.attr('contenteditable',true).stop().css({
				'width':ctpl.width() - menu_width
			}).focus();
		},
		stopEdit:function(){
			var target = this.target;
			var self = this;
			if(target){
				target.removeClass('editing').removeAttr('contenteditable').stop().css({
					'width':self.width()
				});
				self.hideMenu(target)
			}
		},
		addAllMenu:function(selector,opt){
			var self = this;
			opt = opt || {};
			$(selector).each(function(){
				self.addMenu($.extend(opt,{target:$(this)}));
			});
			$(selector).parents('.'+menu_sel)
			.on('click','.'+menu_inner_sel+' li',opt.onMenuItemClick);
		},
		addMenu:function(opt){
			var self = opt.target
			var menu_width = opt.width;
			if(self.parents('.'+menu_sel).length==0){
				menu = $('<div></div>').addClass(menu_sel);
				menu_inner = $('<div></div>').addClass(menu_inner_sel).css({
					'width':menu_width
				}).html(opt.template);
				var li_height = self.height() + (parseInt(self.css('padding-top')) * 2);
				menu_inner.find('li').css({
					'height':li_height+'px',
					'line-height':li_height+'px'
				});
				self.wrap(menu);
				self.after(menu_inner);
			}
		},
		hideMenu:function(target){
			target.siblings('.'+menu_inner_sel).css('visibility','hidden')
		},
		showMenu:function(target){
			target.siblings('.'+menu_inner_sel).css('visibility','visible')
		}
	};
	window.ctpl = ctpl;
})(window,jQuery);